package com.ruoyi.product.service.impl;

import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.product.es.EsProd;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;

import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.product.domain.SysProdAtta;
import com.ruoyi.product.mapper.SysProdMapper;
import com.ruoyi.product.domain.SysProd;
import com.ruoyi.product.service.ISysProdService;

/**
 * 商品列表Service业务层处理
 * 
 * @author tsh
 * @date 2025-08-02
 */
@Service
public class SysProdServiceImpl implements ISysProdService 
{
    @Autowired
    private SysProdMapper sysProdMapper;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;


    /**
     * 查询商品列表
     * 
     * @param prodId 商品列表主键
     * @return 商品列表
     */
    @Override
    public SysProd selectSysProdByProdId(Integer prodId)
    {
        return sysProdMapper.selectSysProdByProdId(prodId);
    }

    /**
     * 查询商品列表列表
     * 
     * @param sysProd 商品列表
     * @return 商品列表
     */
    @Override
    public List<SysProd> selectSysProdList(SysProd sysProd)
    {
        return sysProdMapper.selectSysProdList(sysProd);
    }

    /**
     * 新增商品列表
     * 
     * @param sysProd 商品列表
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSysProd(SysProd sysProd)
    {
        sysProd.setProdStatus(0);
        sysProd.setCreateTime(DateUtils.getNowDate());
        int rows = sysProdMapper.insertSysProd(sysProd);
        insertSysProdAtta(sysProd);
        return rows;
    }

    /**
     * 修改商品列表
     * 
     * @param sysProd 商品列表
     * @return 结果
     */
    @Transactional
    @Override
    public int updateSysProd(SysProd sysProd)
    {
        sysProd.setUpdateTime(DateUtils.getNowDate());
        sysProdMapper.deleteSysProdAttaByProdId(sysProd.getProdId());

        insertSysProdAtta(sysProd);
        return sysProdMapper.updateSysProd(sysProd);
    }

    /**
     * 批量删除商品列表
     * 
     * @param prodIds 需要删除的商品列表主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSysProdByProdIds(Integer[] prodIds)
    {
        sysProdMapper.deleteSysProdAttaByProdIds(prodIds);
        return sysProdMapper.deleteSysProdByProdIds(prodIds);
    }

    /**
     * 删除商品列表信息
     * 
     * @param prodId 商品列表主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSysProdByProdId(Integer prodId)
    {
        sysProdMapper.deleteSysProdAttaByProdId(prodId);
        return sysProdMapper.deleteSysProdByProdId(prodId);
    }

    @Override
    public AjaxResult createIndex() {
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(EsProd.class);
        boolean exists = indexOps.exists();
        if(exists){
           indexOps.delete();
        }
        indexOps.create();
        Document mapping = indexOps.createMapping();
        indexOps.putMapping(mapping);
        return AjaxResult.success("索引创建成功");
    }

    @Override
    public AjaxResult syncProd() {
        //全量同步
        List<SysProd> sysProds = sysProdMapper.selectSysProdList(new SysProd());
        for (SysProd sysProd : sysProds) {
            EsProd esProd = BeanUtil.toBean(sysProd, EsProd.class);
            elasticsearchRestTemplate.save(esProd);
        }
        return AjaxResult.success("同步成功");
    }

    @Override
    public TableDataInfo getListFormEs(SysProd sysProd, Integer pageNum, Integer pageSize) {
       // 构造分页参数
        Integer form=0;
        if(pageNum>0){
            form=pageNum-1;
        }
        PageRequest pageRequest = PageRequest.of(form, pageSize);
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        if(StringUtils.isNotEmpty(sysProd.getProdName())){
            boolQueryBuilder.must(QueryBuilders.fuzzyQuery("prodName",sysProd.getProdName()));
        }
        if(StringUtils.isNotEmpty(sysProd.getProdSpu())){
            boolQueryBuilder.must(QueryBuilders.fuzzyQuery("prodSpu",sysProd.getProdSpu()));
        }

        //排序
        FieldSortBuilder sortBuilder = SortBuilders.fieldSort("prodId").order(SortOrder.DESC);

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("prodName").preTags("<font color='red'>").postTags("</font>");


        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder)
                .withPageable(pageRequest)
                .withSorts(sortBuilder)
                .withHighlightBuilder(highlightBuilder);
        SearchHits<EsProd> searchHits = elasticsearchRestTemplate.search(nativeSearchQueryBuilder.build(), EsProd.class);

        ArrayList<EsProd> list = new ArrayList<>();
        for (SearchHit<EsProd> searchHit : searchHits.getSearchHits()) {
            EsProd esProd = searchHit.getContent();

            List<String> prodName = searchHit.getHighlightField("prodName");
            if(prodName!=null&&prodName.size()>0){
                esProd.setProdName(prodName.get(0));
            }
            list.add(esProd);
        }
        TableDataInfo resData = new TableDataInfo();
        resData.setCode(HttpStatus.SUCCESS);
        resData.setRows(list);
        resData.setMsg("查询成功");
        resData.setTotal(searchHits.getTotalHits());

        return resData;
    }


    /**
     * 新增附件管理信息
     * 
     * @param sysProd 商品列表对象
     */
    public void    insertSysProdAtta(SysProd sysProd)
    {
        List<SysProdAtta> sysProdAttaList = sysProd.getSysProdAttaList();
        Integer prodId = sysProd.getProdId();
        if (StringUtils.isNotNull(sysProdAttaList))
        {
            List<SysProdAtta> list = new ArrayList<SysProdAtta>();
            for (SysProdAtta sysProdAtta : sysProdAttaList)
            {
                sysProdAtta.setCreateTime(new Date());
                sysProdAtta.setCreateBy("admin");
                sysProdAtta.setProdId(prodId);
                list.add(sysProdAtta);
            }
            if (list.size() > 0)
            {
                sysProdMapper.batchSysProdAtta(list);
            }
        }
    }
}
